package ext.drawing;

import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;

import ext.drawing.bean.DrawingsBorrowBean;
import ext.tianma.util.GetSuperior;
import ext.tianma.workflow.BomWorkFlowUtil;
import wt.access.AccessControlHelper;
import wt.access.AccessPermission;
import wt.access.AdHocAccessKey;
import wt.doc.WTDocument;
import wt.doc.WTDocumentMaster;
import wt.enterprise.Master;
import wt.enterprise.RevisionControlled;
import wt.fc.ObjectReference;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.WTObject;
import wt.fc.WTReference;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.method.RemoteMethodServer;
import wt.org.OrganizationServicesHelper;
import wt.org.WTGroup;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.part.WTPartDescribeLink;
import wt.part.WTPartMaster;
import wt.part.WTPartReferenceLink;
import wt.pds.StatementSpec;
import wt.pom.PersistenceException;
import wt.pom.Transaction;
import wt.project.Role;
import wt.query.QueryException;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.team.Team;
import wt.team.TeamManaged;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.Iterated;
import wt.vc.VersionControlException;
import wt.vc.VersionControlHelper;
import wt.vc.config.ConfigHelper;
import wt.vc.config.ConfigSpec;
import wt.vc.config.LatestConfigSpec;
import wt.workflow.definer.WfProcessDefinition;
import wt.workflow.engine.ProcessData;
import wt.workflow.engine.WfEngineHelper;
import wt.workflow.engine.WfEngineServerHelper;
import wt.workflow.engine.WfProcess;

public class BorrowWorkflowUtil {

	/**
	 * 启动图文档借阅流程
	 * 
	 * @param obj
	 * @throws RemoteException
	 * @throws InvocationTargetException
	 * @throws QueryException
	 * @throws WTPropertyVetoException
	 * @throws WTException
	 */
	public static void startDrawingBorrowWorkFlow(WTDocument obj)
			throws RemoteException, InvocationTargetException, QueryException, WTPropertyVetoException, WTException {
		if (!RemoteMethodServer.ServerFlag) {
			RemoteMethodServer.getDefault().invoke("startDrawingBorrowWorkFlow", BorrowWorkflowUtil.class.getName(),
					null, new Class[] { WTDocument.class }, new Object[] { obj });
		} else {
			boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
			WfProcess wfprocess = null;
			String templateName = "图文档借阅流程";
			try {
				WTPrincipal prin = SessionHelper.manager.getPrincipal();
				// 获取流程模板描述
				WfProcessDefinition processDefinition = getProcessDefinition(templateName, obj.getContainer());
				// 创建流程实例
				wfprocess = WfEngineHelper.service.createProcess(processDefinition, obj.getLifeCycleTemplate(),
						obj.getContainerReference());
				// 第一种方法，设置主题
				WfEngineServerHelper.service.setPrimaryBusinessObject(wfprocess, obj);
				// 设置名称
				wfprocess.setName(templateName + " - " + obj.getNumber());
				// 设置创建者
				wfprocess.setCreator(WTPrincipalReference.newWTPrincipalReference(prin));

				// 版本
				String version = getVersionFromDoc(obj);

				// 变量
				ProcessData processData = wfprocess.getContext();

				processData.setValue("versionName", version);

				// 第二种方法，设置主题
				// processData.setValue("primaryBusinessObject", obj);

				// if (variables != null && !variables.isEmpty()) {
				// Iterator keys = variables.keySet().iterator();
				// while (keys.hasNext()) {
				// String key = (String) keys.next();
				// processData.setValue(key, variables.get(key));
				// }
				// }

				// 启动流程
				wfprocess = wfprocess.start(processData, 1, true);
				// wfprocess = wfprocess.start(processData, true,
				// obj.getContainerReference());
			} catch (Exception ex) {
				ex.printStackTrace();
			} finally {
				SessionServerHelper.manager.setAccessEnforced(enforce);
			}

		}
	}

	/**
	 * 获取流程模板描述
	 * 
	 * @param templateName
	 * @param con
	 * @return
	 * @throws WTException
	 */
	public static WfProcessDefinition getProcessDefinition(String templateName, WTContainer con) throws WTException {
		WTContainerRef ref = con.getContainerReference();
		WfProcessDefinition processDefinition = null;
		while (processDefinition == null && con != null) {
			processDefinition = wt.workflow.definer.WfDefinerHelper.service.getProcessDefinition(templateName, ref);
			con = con.getContainer();
		}
		return processDefinition;
	}

	/**
	 * 初始化流程角色
	 * 
	 * @param self
	 * @param roleSuperior
	 *            业务上级
	 * @param roleMender
	 *            修改者
	 * @throws Exception
	 */
	public static void initBorrowAllRole(ObjectReference self, String roleSuperior, String roleMender)
			throws Exception {
		WfProcess process = BomWorkFlowUtil.getProcess(self);// 获取流程
		WTPrincipal principal = SessionHelper.manager.getPrincipal();// 获取session数据
		String superiorName = "testYHM";
		// GetSuperior.getSuperior();
		WTDocument doc = null;
		WTObject wtObject = getPBO(process);
		if (wtObject != null && wtObject instanceof WTDocument) {
			doc = (WTDocument) wtObject;
		}
		String menderName = "testYHM01";// 获取文档的修改者全名
		Team team = null;
		WTUser superior = null;// 业务上级
		WTUser mender = null;// 修改者

		Role superiorRole = Role.toRole(roleSuperior);// 业务上级角色 管理者
														// MANAGER.value
		Role menderRole = Role.toRole(roleMender);// 修改者角色 所有者 OWNER.value

		try {
			team = getTeam(process);// 通过流程实例获取team
			superior = getUserFromName(superiorName);// 通过业务上级名称获取人员对象
			mender = getUserFromName(menderName);// 通过修改者名称获取人员对象
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new WTException(ex);
		}

		// if (superior == null) {
		// throw new WTException("没有找到用户: [" + superior + "] ");
		// } else if (mender == null) {
		// throw new WTException("没有找到用户: [" + mender + "] ");
		// } else if (superior != null || mender != null) {
		// team.addPrincipal(superiorRole, superior);
		// team.addPrincipal(menderRole, mender);
		// }

		if (superior == null) {// 业务上级为空，提示用户没有找到
			throw new WTException("没有找到用户: [" + superior + "] ");
		} else {
			if (mender == null) {// 修改者为空，直接获取管理员
				mender = getUserFromName("Administrator");
			}
			team.addPrincipal(superiorRole, superior);// 设置业务上级
			team.addPrincipal(menderRole, mender);// 设置修改者
		}
		PersistenceHelper.manager.refresh(team);
	}

	/**
	 * 给修改者添加用户
	 * 
	 * @param self
	 * @param internal_value
	 * @param user
	 */
	public static String putOwerUser(ObjectReference self, String internal_value) {
		WfProcess process = BomWorkFlowUtil.getProcess(self);// 获取流程
		String result = "";
		boolean flag = true;
		try {
			WTDocument doc = null;
			WTObject wtObject = getPBO(process);
			if (wtObject != null && wtObject instanceof WTDocument) {
				doc = (WTDocument) wtObject;
			}
			WTUser wtUser = getUserFromName(doc.getModifierName());
			Enumeration em = OrganizationServicesHelper.manager.parentGroups(wtUser);
			while (em.hasMoreElements()) {
				WTGroup group = (WTGroup) ((WTPrincipalReference) em.nextElement()).getObject();
				if ("离职".equals(group.getName())) {
					flag = false;
				}
			}

			// String name = GetSuperior.getSuperior();
			if (!flag) {
				return "fail";
			} else {
				addPrincipalToRole(self, internal_value, wtUser);
				return "succeed";
			}

		} catch (Exception e) {
			result = "fail";
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 给上级主管添加用户
	 * 
	 * @param self
	 * @param internal_value
	 * @return
	 * @throws WTException
	 */
	public static String putDirectorUser(ObjectReference self, String internal_value) throws WTException {
		WfProcess process = BomWorkFlowUtil.getProcess(self);// 获取流程
		String userName = process.getCreator().getName();
		String userName1 = wt.session.SessionHelper.getPrincipal().getName();// 当前登录人
		String result = "";
		try {
			String name = GetSuperior.getSuperior(userName);
			// "zhushenghua";
			// GetSuperior.getSuperior(userName);
			// "yibo_deng";
			// GetSuperior.getSuperior();UPDATE
			if ("fail".equals(name)) {
				return "fail";
			} else {
				WTUser wtUser = getUserFromName(name);
				addPrincipalToRole(self, internal_value, wtUser);
				return "succeed";
			}

		} catch (Exception e) {
			result = "fail";
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 给角色添加用户
	 * 
	 * @param self
	 * @param internal_value
	 * @param user
	 * @throws WTPropertyVetoException
	 * @throws WTException
	 */
	public static void addPrincipalToRole(ObjectReference self, String internal_value, WTUser user)
			throws WTPropertyVetoException, WTException {
		WfProcess process = BomWorkFlowUtil.getProcess(self);// 获取流程实例
		wt.team.Team team = null;
		try {
			team = getTeam(process);// 得到team
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new WTException(ex);
		}

		Role theRole = Role.toRole(internal_value);
		if (user == null) {
			throw new WTException("没有找到用户: [" + user + "] ");
		} else {
			team.addPrincipal(theRole, user);
		}

		PersistenceHelper.manager.refresh(team);
	}

	/**
	 * 流程审批结束后，设置读取权限
	 * 
	 * @param self
	 * @throws WTException
	 * @throws WTPropertyVetoException
	 */
	public static void setAccessForDrawing(ObjectReference self) throws WTException, WTPropertyVetoException {

		boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
		Transaction transaction = new Transaction();
		try {
			transaction.start();
			WfProcess process = BomWorkFlowUtil.getProcess(self);// 获取流程

			ProcessData processData = process.getContext();
			String version = (String) processData.getValue("versionName");

			WTDocument doc = null;
			WTObject wtObject = getPBO(process);
			Vector paramVector = new Vector();
			paramVector.add(AccessPermission.READ);
			paramVector.add(AccessPermission.DOWNLOAD);
			// String version = "";
			if (wtObject != null && wtObject instanceof WTDocument)
				doc = (WTDocument) wtObject;

			if (doc != null) {
				// List<DrawingsBorrowBean> Drawings = BorrowUtil
				// .getDrawingBorrowByNumberAndName(doc.getNumber(),
				// process.getCreator().getName(), version);// 通过文档编号和人员，查询数据表
				// if (Drawings.size() != 0) {
				// for (int i = 0; i < Drawings.size(); i++) {
				// DrawingsBorrowBean db = Drawings.get(i);
				// String state = db.getBorrowState();
				// if (BorrowUtil.BORROW.equals(state)) {
				// version = db.getDrawingsBorrowVersion();
				// }
				// }
				// }
				doc = getWTDocumentByNumAndVersion((WTDocumentMaster) doc.getMaster(), version);
				doc = (WTDocument) AccessControlHelper.manager.setPermissions((wt.access.AdHocControlled) doc,
						process.getCreator(), paramVector, AdHocAccessKey.WNC_ACCESS_CONTROL);
			}
			PersistenceServerHelper.manager.update(doc);
			transaction.commit();
			transaction = null;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (transaction != null)
				transaction.rollback();
			SessionServerHelper.manager.setAccessEnforced(flag);
		}

	}

	/**
	 * 根据部件主数据(master)和视图获取对应最新版本零部件
	 * 
	 * @author Harry Cao
	 * @param master
	 * @param view
	 * @return
	 * @throws WTException
	 */
	public static WTDocument getWTDocumentByNumAndVersion(WTDocumentMaster master, String version) throws WTException {
		WTDocument doc = null;

		// 获取所有版本的零部件
		QueryResult qr = VersionControlHelper.service.allIterationsOf(master);

		while (qr.hasMoreElements()) {
			doc = (WTDocument) qr.nextElement();

			String partVersion = getVersion(doc);
			if (version.equals(partVersion)) {
				return doc;
			}
		}

		return null;
	}

	/**
	 * 权限到期后，收回权限，使用定时器
	 * 
	 * @param self
	 * @throws WTException
	 * @throws WTPropertyVetoException
	 */
	public static void removeAccessForDrawing(ObjectReference self) throws WTException, WTPropertyVetoException {

		boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
		Transaction transaction = new Transaction();
		try {
			transaction.start();
			WfProcess process = BomWorkFlowUtil.getProcess(self);// 获取流程

			ProcessData processData = process.getContext();
			String version = (String) processData.getValue("versionName");

			WTDocument doc = null;
			WTObject wtObject = getPBO(process);
			// String version = "";
			Vector paramVector = new Vector();
			paramVector.add(AccessPermission.READ);
			paramVector.add(AccessPermission.DOWNLOAD);

			if (wtObject != null && wtObject instanceof WTDocument)
				doc = (WTDocument) wtObject;

			if (doc != null) {
				// List<DrawingsBorrowBean> Drawings = BorrowUtil
				// .getDrawingBorrowByNumberAndName(doc.getNumber(),
				// process.getCreator().getName(), version);// 通过文档编号和人员，查询数据表
				// if (Drawings.size() != 0) {
				// for (int i = 0; i < Drawings.size(); i++) {
				// DrawingsBorrowBean db = Drawings.get(i);
				// String state = db.getBorrowState();
				// if (BorrowUtil.BORROW.equals(state)) {
				// version = db.getDrawingsBorrowVersion();
				// }
				// }
				// }
				doc = getWTDocumentByNumAndVersion((WTDocumentMaster) doc.getMaster(), version);
				doc = (WTDocument) AccessControlHelper.manager.removePermissions((wt.access.AdHocControlled) doc,
						process.getCreator(), paramVector, AdHocAccessKey.WNC_ACCESS_CONTROL);
			}

			PersistenceServerHelper.manager.update(doc);
			transaction.commit();
			transaction = null;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (transaction != null)
				transaction.rollback();
			SessionServerHelper.manager.setAccessEnforced(flag);
		}

	}

	/**
	 * 权限回收之后，修改状态
	 * 
	 * @param self
	 * @param state
	 * @throws WTException
	 */
	public static void updateDrawingBorrowState(ObjectReference self, String state) throws WTException {
		WfProcess process = BomWorkFlowUtil.getProcess(self);// 获取流程
		ProcessData processData = process.getContext();
		String version = (String) processData.getValue("versionName");
		WTDocument doc = null;
		WTObject wtObject = getPBO(process);// 获取流程送审对象
		if (wtObject != null && wtObject instanceof WTDocument) {
			doc = (WTDocument) wtObject;// 获取文档
		}
		if (doc != null) {
			BorrowUtil.updateDrawingBorrowState(state, doc.getNumber(), process.getCreator().getName(), version);
		}
	}

	/**
	 * 判断是否权限到期，回收权限
	 * 
	 * @param self
	 * @return
	 * @throws WTException
	 * @throws WTPropertyVetoException
	 * @throws ParseException
	 */
	public static boolean isRecyclingPermissions(ObjectReference self)
			throws WTException, WTPropertyVetoException, ParseException {
		boolean flag = false;
		WfProcess process = BomWorkFlowUtil.getProcess(self);// 获取流程

		ProcessData processData = process.getContext();
		String version = (String) processData.getValue("versionName");

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		WTDocument doc = null;
		WTObject wtObject = getPBO(process);// 获取流程送审对象
		if (wtObject != null && wtObject instanceof WTDocument) {
			doc = (WTDocument) wtObject;// 获取文档
		}
		String endTime = "";
		if (doc != null) {
			List<DrawingsBorrowBean> Drawings = BorrowUtil.getDrawingBorrowByNumberAndName(doc.getNumber(),
					process.getCreator().getName(), version);// 通过文档编号和人员，查询数据表
			if (Drawings.size() != 0) {
				for (int i = 0; i < Drawings.size(); i++) {
					DrawingsBorrowBean db = Drawings.get(i);
					String state = db.getBorrowState();
					if (BorrowUtil.BORROW.equals(state)) {
						endTime = db.getBorrowEndDate();// 获取借阅时间
					}
				}
			}
		}
		// 设置时区
		// TimeZone tz = WTContext.getContext().getTimeZone();
		// TimeZone.setDefault(tz);
		Date currentDate = new Date();// 当前时间
		if (!"".equals(endTime)) {
			Date endDate = simpleDateFormat.parse(endTime);// 借阅结束时间
			if (currentDate.after(endDate)) {// 当前时间大于借阅结束时间
				flag = true;
			}
		}
		return flag;
	}

	/**
	 * 根据流程获取流程主对象
	 * 
	 * @param wfprocess
	 * @return
	 * @throws WTException
	 */
	public static WTObject getPBO(WfProcess wfprocess) throws WTException {
		WTObject wtobject = null;
		ReferenceFactory referencefactory = new ReferenceFactory();
		WTReference wtreference = wfprocess.getBusinessObjectReference(referencefactory);
		if (wtreference == null && wfprocess.isNested()) {
			wtobject = (WTObject) wfprocess.getContext().getValue("primaryBusinessObject");
		}
		if (wtreference != null && wtreference.getKey() != null) {
			wtobject = (WTObject) wtreference.getObject();
		}
		return wtobject;
	}

	/**
	 * 获取对象的大小版本组成的版本序列值，形如： A.1
	 * 
	 * @param revisionControlled
	 * @return
	 */
	/**
	 * @param revisionControlled
	 * @return
	 */
	public static String getVersion(RevisionControlled revisionControlled) {

		String version = "";

		if (revisionControlled != null) {
			// 获取大版本
			String majorVersion = revisionControlled.getVersionIdentifier().getValue();

			// 获取小版本
			String minorVersion = revisionControlled.getIterationIdentifier().getValue();

			version = majorVersion + "." + minorVersion;
		}

		return version;
	}

	/**
	 * 获取文档版本
	 * 
	 * @param doc
	 * @return
	 */
	public static String getVersionFromDoc(WTDocument doc) {
		String version = null;
		try {
			version = VersionControlHelper.getIterationDisplayIdentifier(doc).toString();
		} catch (VersionControlException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return version;
	}

	/**
	 * 根据用户名得到用户
	 * 
	 * @param name
	 * @return
	 * @throws WTException
	 */
	public static WTUser getUserFromName(String name) throws WTException {
		Enumeration enumUser = OrganizationServicesHelper.manager.findUser(WTUser.NAME, name);
		WTUser user = null;
		if (enumUser.hasMoreElements())
			user = (WTUser) enumUser.nextElement();

		if (user == null) {
			enumUser = OrganizationServicesHelper.manager.findUser(WTUser.FULL_NAME, name);
			if (enumUser.hasMoreElements())
				user = (WTUser) enumUser.nextElement();
		}

		if (user == null) {
			throw new WTException("系统中不存在用户名为'" + name + "'的用户！");
		}

		return user;
	}

	/**
	 * 根据WfProcess对象，获得团队
	 * 
	 * @param process
	 * @return
	 * @throws Exception
	 */
	public static Team getTeam(WfProcess process) throws Exception {

		Team team = null;
		ReferenceFactory rf = new ReferenceFactory();
		String oid = rf.getReferenceString(process);
		WTObject wtobject = (WTObject) rf.getReference(oid).getObject();
		if (wtobject instanceof TeamManaged) {
			team = (Team) ((TeamManaged) wtobject).getTeamId().getObject();
		} else if (wtobject instanceof Team) {
			team = (Team) wtobject;
		}
		return team;
	}

	/**
	 * 根据WTPartMaster获得最新版WTPart
	 * 
	 * @param partMaster
	 * @return
	 * @throws Exception
	 */
	public static WTPart getLatestPart(WTPartMaster partMaster) throws Exception {
		WTPart part = null;
		if (partMaster != null) {
			QueryResult qr = VersionControlHelper.service.allVersionsOf(partMaster);
			if (qr != null && qr.hasMoreElements()) {
				part = (WTPart) qr.nextElement();
			}
		}
		return part;
	}

	/**
	 * 根据part得到参考关系的文档集合
	 * 
	 * @param part
	 * @return
	 * @throws WTException
	 */
	public static List<WTDocument> getReferenceDoc(WTPart part) throws WTException {
		List<WTDocument> result = new ArrayList<WTDocument>();
		try {
			if (!RemoteMethodServer.ServerFlag) {
				RemoteMethodServer.getDefault().invoke("getReferenceDoc", BorrowWorkflowUtil.class.getName(), null,
						new Class[] { WTPart.class }, new Object[] { part });
			} else {
				boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
				QueryResult qr = PersistenceHelper.manager.navigate(part, WTPartReferenceLink.REFERENCES_ROLE,
						WTPartReferenceLink.class, false);
				try {
					while (qr.hasMoreElements()) {
						WTPartReferenceLink link = (WTPartReferenceLink) qr.nextElement();
						if (link != null) {
							WTDocumentMaster master = link.getReferences();
							WTDocument d = (WTDocument) getLatestRevision(master);
							result.add(d);
						}
					}
					return result;
				} catch (Exception e) {

				} finally {
					SessionServerHelper.manager.setAccessEnforced(enforce);
				}
			}
		} catch (Exception e) {

		}
		return null;
	}

	/**
	 * 根据part得到描述关系的文档集合
	 * 
	 * @param part
	 * @return
	 * @throws WTException
	 */
	public static List<WTDocument> getDescribeDoc(WTPart part) throws WTException {
		List<WTDocument> result = new ArrayList<WTDocument>();
		try {
			if (!RemoteMethodServer.ServerFlag) {
				RemoteMethodServer.getDefault().invoke("getDescribeDoc", BorrowWorkflowUtil.class.getName(), null,
						new Class[] { WTPart.class }, new Object[] { part });
			} else {
				boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
				QueryResult qr = PersistenceHelper.manager.navigate(part, WTPartDescribeLink.DESCRIBED_BY_ROLE,
						WTPartDescribeLink.class, false);
				try {
					while (qr.hasMoreElements()) {
						WTPartDescribeLink link = (WTPartDescribeLink) qr.nextElement();
						if (link != null) {
							WTDocument d = link.getDescribedBy();
							d = getLatestDocument((WTDocumentMaster) d.getMaster());
							result.add(d);
						}
					}
					return result;
				} catch (Exception e) {

				} finally {
					SessionServerHelper.manager.setAccessEnforced(enforce);
				}
			}
		} catch (Exception e) {

		}
		return null;
	}
	
	/**
	 * 根据WTDocumentMaster获得最新版WTDocument
	 * 
	 * @param docMaster
	 * @return
	 * @throws WTException
	 * @throws PersistenceException
	 * @throws Exception 
	 * @throws Exception
	 */
	public static WTDocument getLatestDocument(WTDocumentMaster docMaster) throws PersistenceException, WTException, Exception {
		Iterated iter=null; 
		boolean flag=false;
		LatestConfigSpec latestconfigspec = new LatestConfigSpec();
		QueryResult queryresult = ConfigHelper.service.filteredIterationsOf(docMaster, latestconfigspec);
		if(queryresult.size()<=0){
			ConfigSpec configspec = ConfigHelper.service.getDefaultConfigSpecFor(WTDocumentMaster.class);
			queryresult = ConfigHelper.service.filteredIterationsOf(docMaster, configspec);
		}		
		while( queryresult.hasMoreElements() && (!flag) ){ 
			iter=(Iterated)(queryresult.nextElement());
			flag= iter.isLatestIteration();
		}
		return (WTDocument)iter;
	}

	/**
	 * 根据master得到 doc
	 * 
	 * @param master
	 * @return
	 */
	public static RevisionControlled getLatestRevision(Master master) {
		try {
			if (!RemoteMethodServer.ServerFlag) {
				return (RevisionControlled) RemoteMethodServer.getDefault().invoke("getLatestRevision",
						BorrowWorkflowUtil.class.getName(), null, new Class[] { Master.class },
						new Object[] { master });
			} else {
				boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
				RevisionControlled rc = null;
				if (master != null) {
					try {
						QueryResult qr = VersionControlHelper.service.allVersionsOf(master);
						while (qr.hasMoreElements()) {
							RevisionControlled obj = (RevisionControlled) qr.nextElement();
							if ((rc == null) || (obj.getVersionIdentifier().getSeries()
									.greaterThan(rc.getVersionIdentifier().getSeries()))) {
								rc = obj;
							}
						}
						if (rc != null)
							rc = (RevisionControlled) VersionControlHelper.getLatestIteration(rc, false);
					} catch (WTException e) {

					} finally {
						SessionServerHelper.manager.setAccessEnforced(enforce);
					}
				}
				return rc;
			}
		} catch (Exception e) {

		}
		return null;
	}

	/**
	 * 根据编号查找文档
	 * 
	 * @param number
	 * @return
	 * @throws WTException
	 */
	public static WTDocument getDocByNumber(String number) throws WTException {
		QuerySpec qs = new QuerySpec(WTDocument.class);
		SearchCondition sc = new SearchCondition(WTDocument.class, WTDocument.NUMBER, SearchCondition.EQUAL, number,
				false);// 写条件
						// 最后一个false是忽略大小写
		qs.appendWhere(sc, new int[] { 0 });
		QueryResult qr = PersistenceHelper.manager.find((StatementSpec) qs);
		while (qr.hasMoreElements()) {
			Object obj = qr.nextElement();
			if (obj instanceof WTDocument) {
				WTDocument doc = (WTDocument) obj;
				return doc;
			}
		}
		return null;
	}

	/**
	 * 根据天数，往后增加时间，跳过法定节假日以及周末
	 * 
	 * @param beginTimeStr
	 *            开始时间字符串 yyyy-MM-dd HH:mm:ss
	 * @param sum
	 *            往后增加的天数 5
	 * @return 增加后的时间字符串 yyyy-MM-dd HH:mm:ss
	 * @throws ParseException
	 */
	public static String increaseDateByDay(String beginTimeStr, Integer sum) throws ParseException {
		HolidayUtil h = new HolidayUtil();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 保存格式
		SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");// 校验格式

		Date beginTime = formatter.parse(beginTimeStr);
		Date endTime = null;
		Date tempTime = beginTime;
		Calendar c = Calendar.getInstance();

		int i = 1;
		while (i <= sum) {
			c.setTime(tempTime);
			c.add(Calendar.DAY_OF_MONTH, 1);
			tempTime = c.getTime();
			boolean flag = h.isWorkDay(f.format(tempTime));// 判断是否为工作日
			if (flag) {
				i++;
			}
		}

		endTime = tempTime;
		String endTimeStr = formatter.format(endTime);
		return endTimeStr;
	}

	/**
	 * 流程结束后修改状态和借阅时间、版本
	 * 
	 * @param docNumber
	 *            文档编号
	 * @param user
	 *            用户
	 * @param oldVersion
	 *            旧版本
	 * @param newVersion
	 *            新版本
	 * @param dayNum
	 *            天数
	 * @param state
	 *            状态
	 * @throws NumberFormatException
	 * @throws ParseException
	 */
	public static void updateDrawingBorrowVersionAndStateAndBorrowDate(String docNumber, String user, String oldVersion,
			String newVersion, String dayNum, String state) throws NumberFormatException, ParseException {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// 设置时区
		// TimeZone tz = WTContext.getContext().getTimeZone();
		// TimeZone.setDefault(tz);
		Date currentDate = new Date();
		String beginTimeStr = simpleDateFormat.format(currentDate);
		String endTimeStr = BorrowWorkflowUtil.increaseDateByDay(beginTimeStr, Integer.parseInt(dayNum));// 获取借阅结束时间
		BorrowUtil.updateDrawingBorrowVerionAndStateAndDate(state, beginTimeStr, endTimeStr, docNumber, user,
				oldVersion, newVersion);// 更新数据

	}

}
